# coding=utf-8
import tornado.web

import WrapCursor
from CommonLib import *
from database.models.Controller import Controller
from database.models.DatabaseCommon import *


class GetDeviceInfoHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            id = ojson['id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except Exception as e:
            self.write(r.Error('request data error' + e.message))
            return
        sql = None
        ret = ""
        data_set = None
        col_name = None

        s = Session()
        if id == -1:
            sql = """
                select * from Controller where name!=''
            """
            c = s.query(Controller).all()
        else:
            sql = """
                select * from Controller where id =? and name!=''
            """
            c = s.query(Controller).filter_by(id=id).all()
        jsonret = dict()
        jsonret['Code'] = 0
        data = list()
        jsonret['data'] = data
        jsonret['desc'] = '查询成功'
        for i in c:
            o = dict()
            o['HardID'] = i.HardID
            o['Type'] = i.TypeID
            o['id'] = i.id
            o['value'] = i.Value
            o['Name'] = i.Name
            data.append(o)
        self.write(json.dumps(jsonret))
